<?php


namespace App\Crontab;


use App\Model\DataTable;
use App\Model\User;
use App\Model\Wechat;
use App\Utility\Pool\MysqlPool;
use App\Utility\Queue\QueueType;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\EasySwoole\Task\TaskManager;

class DailyTask extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        return '@daily';
    }

    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        return 'DailyTask';
    }

    function run(int $taskId, int $workerIndex)
    {
        // TODO: Implement run() method.
        TaskManager::getInstance()->async(function () {
            //同步关注用户信息
            DailyTask::getFollowUser();
        });

    }

    function onException(\Throwable $throwable, int $taskId, int $workerIndex)
    {
        // TODO: Implement onException() method.
    }

    //同步关注用户信息
    public static function getFollowUser()
    {
        $wechat = new Wechat();
        $client = $wechat->GetClient();

        $req = $client->officialAccount()->user()->list();
        $get_flag = true;
        $newopenid = null;
        User::cleanfollow();
        while ($get_flag) {
            try {
                $req = $client->officialAccount()->user()->list($newopenid);
            } catch (\Exception $e) {
                $get_flag = false;
            }
            if ($req['count'] > 0) {
                $templist = array();
                foreach ($req['data']['openid'] as $item) {
                    //每300个更新
                    array_push($templist, $item);
                }
                if (count($templist) > 0) {
                    User::setfollow($templist);
                }
                /**
                 * $templist = array();
                 * $count = 1;
                 * foreach ($req['data']['openid'] as $item){
                 * //每300个更新
                 * array_push($templist,$item);
                 * $count++;
                 * if($count > 300){
                 * User::setfollow($templist);
                 * $templist = array();
                 * $count = 1;
                 * }
                 * }
                 * if(count($templist)>0){
                 * User::setfollow($templist);
                 * }
                 **/
            }
            $newopenid = $req['next_openid'];
            if ($newopenid == null) {
                $get_flag = false;
            }
        }
    }


    //给新注册的用户加积分
    public static function newUserScore()
    {
        $now = time() - 259200;
        $db = MysqlPool::defer();

        $count = $db
            ->join('cz_user as u ', 'u.id = t.user_id')
            ->where('t.createtime', $now, '>')
            ->where('u.score', 100, '<')
            ->where('t.is_follow', 1)
            ->count(DataTable::THIRD_TABLE . ' as t ');

        $page_size = QueueType::MESSAGE_GUESS_COUNT;
        $pages = (int)$count / $page_size;
        if ($pages < 1) {
            self::getFollowUserlist($db, null, $now);

        } else {
            for ($page = 0; $page < $pages - 1; $page++) {
                self::getFollowUserlist($db, [$page * $page_size, $page_size], $now);
            }
            //取余数
            $mod = $count % $page_size;
            if ($mod > 0) {
                self::getFollowUserlist($db, [$count - $mod, $mod], $now);
            }
        }

    }

    private static function getFollowUserlist($db, $limit, $now)
    {
        $userlist = $db
            ->join('cz_user as u ', 'u.id = t.user_id')
            ->where('t.createtime', $now, '>')
            ->where('u.score', 100, '<')
            ->where('t.is_follow', 1)
            ->get(DataTable::THIRD_TABLE . ' as t ', $limit, 'u.id,u.score');
        //var_dump($userlist);
        foreach ($userlist as $item) {
            $score = 100 - $item['score'];

            if ($score > 0) {

                User::score($db, $score, $item['id'], '新关注用户小于100每天加到100积分');
            }

        }


    }

}